
<style scoped>
.item-yc{
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow:ellipsis;
}

</style>

<template>
  <div>
    <div class="search" style="display: flex">
      <el-input placeholder="请输入账号查询" style="width: 200px" v-model="searchValue"></el-input>
      <div style="display: flex;margin-left: 10px">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
        <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      </div>
    </div>



    <div class="table" style="user-select: none">
      <el-table :data="tableData" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column label="房间图片">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 40px; height: 40px; border-radius: 50%" v-if="scope.row.imageList" :src="visitPath()+scope.row.imageList[0].img"
                :preview-src-list="imgListFun(scope.row.imageList)"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="roomName" width="120" label="房间名称"></el-table-column>
        <el-table-column prop="roomNumber" label="房间号"></el-table-column>
        <el-table-column prop="price" label="房间价格">
          <template v-slot="scope">{{scope.row.price}}元</template>
        </el-table-column>
        <el-table-column prop="hotelInfo.name" width="140" label="所属民宿"></el-table-column>
        <el-table-column prop="hotelInfo.price" label="起步价">
          <template v-slot="scope">{{scope.row.hotelInfo.price}}元</template>
        </el-table-column>
        <el-table-column prop="grade" width="200" label="现等级">
          <template v-slot="scope">
            <el-rate
                v-model="scope.row.grade"
                disabled
                :max="6"
                show-score
                text-color="#ff9900"
                score-template="{value}">
            </el-rate>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="现评分"></el-table-column>
        <el-table-column prop="deviceList" width="200" label="房间设备">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top" :content="deviceListFun(scope.row.deviceList)" >
                <div class="item-yc" style="width: 220px">{{deviceListFun(scope.row.deviceList)}}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" width="320" label="房间描述">
          <template v-slot="scope">
           <div>
             <el-tooltip placement="top" :content="scope.row.description" >
               <div class="item-yc">{{scope.row.description}}</div>
             </el-tooltip>
           </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination background @current-change="handleCurrentChange" :current-page="pageNum"
          :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, prev, pager, next" :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog :title="dialogTitle" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 50px;user-select: none" :rules="rules" ref="formRef">
        <el-form-item label="绑定酒店"  prop="hotelId">
          <el-select v-model="form.hotelId" placeholder="请选择酒店" style="width: 100%">
            <el-option
                v-for="item in hotalList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #f60101; font-size: 13px">{{ item.price }} 元起</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间图片"  prop="imageList">
         <div style="display: flex;  align-items: center;">
           <div v-if="form.imageList.length>=1">
             <el-image style="width: 30px;height: 30px;border-radius: 50%;" :src="visitPath()+form.imageList[0].img"></el-image>
           </div>
          <div style="margin-left: 10px;">
            <el-upload class="avatar-uploader" :style="form.imageList.length>=1?'margin-top: -8px':''" :action="upladPath()" :show-file-list="false"
                       :on-success="handleAvatarSuccess">
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </div>
         </div>
        </el-form-item>
        <el-form-item label="房间名称"  prop="roomName">
          <el-input v-model="form.roomName" maxlength="20" placeholder="请填写房间名称"></el-input>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber" >
          <el-input v-model="form.roomNumber" maxlength="5" type="number" placeholder="请填写房间号"></el-input>
        </el-form-item>
        <el-form-item label="房间价格" prop="price">
          <el-input v-model="form.price" type="number" maxlength="5" placeholder="请填写房间价格"></el-input>
        </el-form-item>
        <el-form-item label="房间设备" prop="deviceList">
          <el-select
              v-model="deviceList"
              multiple
              collapse-tags
              @blur="deviceListChangeFun()"
              style="width: 100%"
              placeholder="请选择">
            <el-option
                v-for="item in dict5"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间描述" prop="description">
          <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入房间描述"
              v-model="form.description">
          </el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {upladPath, visitPath} from "@/Interface/FileApi";
import {addRoom, deleteRoom, deleteRooms, queryRoomPage, updateRoom} from "@/Interface/RoomApi";
import {backLogin, deviceListFun, imgListFun} from "@/Config/Tool";
import {queryDictItem} from "@/Interface/DictApi";
import {queryHotelPage} from "@/Interface/HotelApi";

export default {
  name: "Admin",
  data() {
    return {
      dialogTitle:"新增房型",
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      name: null,
      searchValue:null,
      fromVisible: false,
      deviceList:[],
      hotalList:[],
      form: {
        "hotelId": null,
        "roomName": null,
        "roomNumber": null,
        "imageList": [],//[{img:''}]
        "price": null,
        "remaker": null,
        "score": "10.0",
        "review": "0",
        "grade": 5,
        "deviceList": [],//[{color:'',title:''}]
        "description": null
      },
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        hotelId: [
          { required: true, message: '酒店不能为空', trigger: 'blur' },
        ],
        roomName: [
          { required: true, message: '房间名称不能为空', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
        ],
        roomNumber: [
          { required: true, message: '房间号不能为空', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '房间描述不能为空', trigger: 'blur' },
        ],

        imageList:[
          { required: true, message: '设备信息不能为空', trigger: 'blur' },
        ]
      },
      ids: [],
      dict5:[]
    }
  },
  watch:{
    searchValue(newValue,oldValue){
      if (newValue){
        queryRoomPage({
          limit:10000,
          page:1,
          param:{}
        }).then(res => {
          if (res.code === 200) {
            const result = res.data?.records.filter(item => {
               return Object.values(item).some(val => val?.toString().includes(newValue));
             });
            this.tableData= result;
          } else {
            this.$message.error(res.msg)
          }
        })
      }else {
        this.load(1);
      }
    }
  },
  created() {
    backLogin("ADMIN")
    this.load(1);
    this.queryDictItemFun([5])
  },
  methods: {
    deviceListFun,
    imgListFun,
    visitPath() {
      return visitPath
    },
    upladPath() {
      return upladPath
    },
    handleAdd() {
      queryHotelPage({
        limit:10000,
        page:1,
        param:{}
      }).then(res => {
        if (res.code === 200) {
          this.hotalList = res.data?.records
        } else {
          this.$message.error(res.msg)
        }
      })
      this.dialogTitle="新增房型";
      this.form = {
          "hotelId": null,
          "roomName": null,
          "roomNumber": null,
          "imageList": [],//[{img:''}]
          "price": null,
          "remaker": null,
          "score": "10.0",
          "review": 0,
          "grade": 5,
          "label": "5",
          "deviceList": [],//[{color:'',title:''}]
          "description": null
      }  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      this.dialogTitle="修改房型";
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      let list =[];
      this.form.deviceList.map(item=>{
        this.dict5.map(item2=>{
          if (item.label==item2.label){
            list.push(item2.value)
          }
        })
      })
      this.deviceList = list;
      this.fromVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if(this.form.id){
            let list =[]
            this.dict5.map(item=>{
              this.deviceList.map(item2=>{
                if (item.value==item2){
                  list.push({"color":'',"label":item.label})
                }
              })
            })
            this.form.deviceList=list;
            updateRoom(this.form).then(res => {
              if (res.code === 200) {  // 表示成功保存
                this.$message.success(res.msg)
                setTimeout(()=>{
                  this.load(1)
                },1000)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
              }
            })
          }else {
            let list =[]
            this.dict5.map(item=>{
              this.deviceList.map(item2=>{
                if (item.value==item2){
                  list.push({"color":'',"label":item.label})
                }
              })
            })
            this.form.deviceList=list;
            addRoom(this.form).then(res => {
              if (res.code === 200) {  // 表示成功保存
                this.$message.success(res.msg)
                setTimeout(()=>{
                  this.load(1)
                },1000)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
              }
            })
          }
        }
      })
    },
    del(id) {
      this.$confirm('您确定删除吗？', '确认删除', { type: "warning" }).then(response => {
        deleteRoom({id}).then(res => {
          if (res.code === '200') {
            this.$message.success(res.msg)
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', { type: "warning" }).then(response => {
        deleteRooms( {deleteIds: this.ids }).then(res => {
          if (res.code === 200) {   // 表示操作成功
            this.$message.success(res.msg)
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      queryRoomPage({
        limit:this.pageSize,
        page:this.pageNum,
        param:{}
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data?.records
          this.total = res.data?.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    reset() {
      this.name = null
      this.load(1)
    },
    /**
     * 设备信息转换
     */
    deviceListChangeFun(){
      let list =[]
       this.dict5.map(item=>{
        this.deviceList.map(item2=>{
          if (item.value==item2){
            list.push({"color":'',"label":item.label})
          }
        })
      })
      this.form.deviceList=list;
    },
    /**
     * 文件上传
     */
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.code==="200"){
        this.$message.success('上传成功');
        this.form.imageList = this.form.imageList.concat([{"img":response.data.fileName}]);
      }else {
        this.$message.error("文件上传失败");
      }
    },
    /**
     * 查询字典值
     */
    queryDictItemFun(e){
      e.forEach(item=>{
        queryDictItem({id:item}).then(res=>{
          switch (item){
            case 2:
              this.dict2 = res.data;
              break;
            case 3:
              this.dict3 = res.data;
              break;
            case 4:
              this.dict4 = res.data;
              break;
            case 5:
              this.dict5 = res.data;
              break;
            default:
              this.dict4 = res.data;
              break;
          }
        })
      })
    },
  }
}
</script>
